package edu.xust.utils;

import java.lang.reflect.Field;
import java.util.Map;
import java.util.Set;

/**
 * javabean工具类
 */
public class BeanUtils {
    /**
     * 从requestmap中获取数值对应拷贝给 目标对象
     * @param map
     * @param target
     */
    public static void copyPropertiesFromRequestMap(Map<String, String[]> map,Object target) throws IllegalAccessException {
        Set<Map.Entry<String, String[]>> set = map.entrySet();//获得map的值
        Class clazz = target.getClass();//得到目标对象的类对象
        Field[] fds = clazz.getDeclaredFields();//得到目标对象的成员变量数组
        for(Map.Entry<String,String[]> entry:set){
            for(Field fd : fds){
                if(entry.getKey().equals(fd.getName())){//如果循环到的requestmap的属性名 和   目标对象的 属性名一致就拷贝值'
                   copyValueByType(fd,target,entry.getValue()[0]);
                }
            }
        }
        
    }

    /**
     * 将request对应的值拷贝给目标对象对应的字段
     * @param fd 字段
     * @param target 目标对象
     * @param value  值
     */
    private static void copyValueByType(Field fd , Object target,Object value) throws IllegalAccessException {
        fd.setAccessible(true);
        String typeName = fd.getType().getSimpleName();
        switch (typeName){
            case "String":
                System.out.println(value);
                fd.set(target, String.valueOf(value));
                break;
            case "byte":;
            case "Byte":
                fd.setByte(target, Byte.parseByte(value.toString()));
                break;
            case "short":;
            case "Short":
                fd.setShort(target, Short.parseShort(value.toString()));
                break;
            case "int":;
            case "Integer":
                fd.setInt(target, Integer.parseInt(value.toString()));
                break;
            case "long":;
            case "Long":
                fd.setLong(target, Long.parseLong(value.toString()));
                break;
            case "float":;
            case "Float":break;
            case "double":;
            case "Double":break;
            case "boolean":;
            case "Boolean":break;
            case "char":;
            case "Character":break;
            default:
                fd.set(target, value);
                break;
        }


    }
}
